<?php


namespace app\xiangji\services;


use app\common\models\UserWallet;

class WalletService
{
    /**
     * @todo 校验钱包账户合法性
     * @param UserWallet $wallet    钱包对象
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function checkWalletSecurity(UserWallet $wallet)
    {
        $last_wallet_log = $wallet->logs()->order('id', 'desc')->field(['id', 'wallet_id','amount_after'])->find();
        // 钱包初始化状态：无钱包日志数据且钱包金额为空
        if ($wallet->balance == 0 && is_null($last_wallet_log)) return true;
        return $wallet->balance == $last_wallet_log->amount_after;
    }

    /**
     * 钱包日志创建
     * @param UserWallet $wallet    钱包对象
     * @param int $amount           变动金额：正数增加，负数消费
     * @param string $scene         变动场景描述
     * @return false|\think\Model
     */
    public static function createWalletLog(UserWallet $wallet, int $amount, string $scene = '游戏获得')
    {
        return $wallet->logs()->save([
            'user_id'       => $wallet->user_id,
            'change'        => $amount, // 提现减少，所以应为负数
            'scene'         => $scene,
            'amount_before' => $wallet->balance,
            'amount_after'  => $wallet->balance + $amount
        ]);
    }

    /**
     * @todo 更新用户钱包数据
     * @param UserWallet $wallet    用户钱包对象
     * @param int $amount           钱包变动值
     * @return bool
     */
    public static function updateWallet(UserWallet $wallet, int $amount)
    {
        return $wallet->save([
            'balance'   => $wallet->balance + $amount,
            'income'    => $amount > 0 ? ($wallet->income + $amount) : $wallet->income,
            'outcome'   => $amount < 0 ? ($wallet->outcome - $amount) : $wallet->outcome,
        ]);
    }
}
